package com.one.react.internal;

import com.sun.source.tree.Tree;
import com.sun.tools.javac.parser.JavacParser;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.tree.TreeScanner;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.Names;

public class FieldTypeAndInitTranslator extends TreeScanner {
    private Context context;
    private TreeMaker F;
    private Names names;

    public FieldTypeAndInitTranslator(Context context) {
        this.context = context;
        this.F = TreeMaker.instance(context);
        this.names = Names.instance(context);
    }

    @Override
    public void visitTopLevel(JCTree.JCCompilationUnit tree) {
        for (JCTree def : tree.defs) {
            if (def.getKind() == Tree.Kind.CLASS) {
                scan(def);
            }
        }
    }

    @Override
    public void visitClassDef(JCTree.JCClassDecl tree) {
        for (JCTree def : tree.defs) {
            if (def.getKind() == Tree.Kind.VARIABLE) {
                scan(def);
            }
        }
    }

    @Override
    public void visitVarDef(JCTree.JCVariableDecl tree) {
        if (tree.sym.isLocal()) {
            return;
        }
        tree.init = translateVarInit(tree);
        tree.vartype = translateVarType(tree);
    }

    private JCTree.JCExpression translateVarType(JCTree.JCVariableDecl tree) {
        JCTree.JCExpression vartype = MyParser.getInstance(context)
                .getParserFor("com.one.react.Observable<" + tree.vartype + ">")
                .parseType();
        return vartype;
    }

    private JCTree.JCExpression translateVarInit(JCTree.JCVariableDecl tree) {
        JCTree.JCExpression init = MyParser.getInstance(context)
                .getParserFor("new com.one.react.Observable<>(" + tree.init + ")")
                .parseExpression();
        return init;
    }
}
